<?php
class Tenpay {
	private $config  = array(
		'partner' => '1218675901',
		'key'     => '75e18358e57053bb743a8ba7e77966c3',
		"return_url"	=> 'http://www.class100.com/user_respond.htm',
		"notify_url"	=> 'http://www.class100.com/tenNotify.htm',
		'trade_mode' => '1'
	);
	public function pay($data){
		require ("RequestHandler.class.php");
		/* 获取提交的订单号 */
		$out_trade_no = $data["id"];
		/* 获取提交的商品名称 */
		$product_name = $data["WIDsubject"];
		/* 获取提交的商品价格 */
		$order_price = $data["online_money"];
		/* 获取提交的备注信息 */
		$remarkexplain = $data["WIDbody"];
		
		$bank_type = $data['bank_type'];
		/* 支付方式 */
		$trade_mode= $this->config['trade_mode'];
		$strDate = date("Ymd");
		$strTime = date("His");
		/* 商品价格（包含运费），以分为单位 */
		$total_fee = $order_price*100;
		/* 商品名称 */
		$desc = "商品：".$product_name.",备注:".$remarkexplain;
		/* 创建支付请求对象 */
		$reqHandler = new RequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($this->config['key']);
		$reqHandler->setGateUrl("https://gw.tenpay.com/gateway/pay.htm");
		//设置支付参数
		$reqHandler->setParameter("partner", $this->config['partner']);
		$reqHandler->setParameter("out_trade_no", $out_trade_no);
		$reqHandler->setParameter("total_fee", $total_fee);  //总金额
		$reqHandler->setParameter("return_url", $this->config['return_url'].'?code=tenpay&pay_log_id='.$data['pay_log_id']);
		$reqHandler->setParameter("notify_url", $this->config['notify_url']);
		$reqHandler->setParameter("body", $desc);
		$reqHandler->setParameter("bank_type", $bank_type);  	  //银行类型，默认为财付通
		//用户ip
		$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);//客户端IP
		$reqHandler->setParameter("fee_type", "1");               //币种
		$reqHandler->setParameter("subject",$desc);          //商品名称，（中介交易时必填）
		//系统可选参数
		$reqHandler->setParameter("sign_type", "MD5");  	 	  //签名方式，默认为MD5，可选RSA
		$reqHandler->setParameter("service_version", "1.0"); 	  //接口版本号
		$reqHandler->setParameter("input_charset", "utf-8");   	  //字符集
		$reqHandler->setParameter("sign_key_index", "1");    	  //密钥序号
		//业务可选参数
		$reqHandler->setParameter("attach", "");             	  //附件数据，原样返回就可以了
		$reqHandler->setParameter("product_fee", "");        	  //商品费用
		$reqHandler->setParameter("transport_fee", "0");      	  //物流费用
		$reqHandler->setParameter("time_start", date("YmdHis"));  //订单生成时间
		$reqHandler->setParameter("time_expire", "");             //订单失效时间
		$reqHandler->setParameter("buyer_id", "");                //买方财付通帐号
		$reqHandler->setParameter("goods_tag", "");               //商品标记
		$reqHandler->setParameter("trade_mode",$trade_mode);              //交易模式（1.即时到帐模式，2.中介担保模式，3.后台选择（卖家进入支付中心列表选择））
		$reqHandler->setParameter("transport_desc","");              //物流说明
		$reqHandler->setParameter("trans_type","1");              //交易类型
		$reqHandler->setParameter("agentid","");                  //平台ID
		$reqHandler->setParameter("agent_type","");               //代理模式（0.无代理，1.表示卡易售模式，2.表示网店模式）
		$reqHandler->setParameter("seller_id","");                //卖家的商户号
		//请求的URL
		$reqUrl = $reqHandler->getRequestURL();
		//获取debug信息,建议把请求和debug信息写入日志，方便定位问题
		$debugInfo = $reqHandler->getDebugInfo();
		$html =  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
					<html xmlns="http://www.w3.org/1999/xhtml">
					<head>
					<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
					<title>财付通支付</title>
					</head>
					<body>
				<form action="'.$reqHandler->getGateUrl().'" id="forma" method="post" >';
		$params = $reqHandler->getAllParameters();
		foreach($params as $k => $v) {
			$html = $html.'<input type="hidden" name="'.$k.'" value="'.$v.'" />';
		}
		$html= $html.'<input type="submit" value="财付通支付"></form> <script>document.forms["forma"].submit();</script></body></html>';
		return $html;
	}
	public function notify($data){
		require ("ResponseHandler.class.php");
		require ("RequestHandler.class.php");
		require ("ClientResponseHandler.class.php");
		require ("TenpayHttpClient.class.php");
		require ("function.php");
		log_result("进入后台回调页面");
		/* 创建支付应答对象 */
		unset($data['control']);
		unset($data['module']);
		$resHandler = new ResponseHandler($data);
		$resHandler->setKey($this->config['key']);
		//判断签名

		if($resHandler->isTenpaySign()) {
			//通知id
			$notify_id = $resHandler->getParameter("notify_id");
			//通过通知ID查询，确保通知来至财付通
			//创建查询请求
			$queryReq = new RequestHandler();
			$queryReq->init();
			$queryReq->setKey($this->config['key']);
			$queryReq->setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml");
			$queryReq->setParameter("partner", $this->config['partner']);
			$queryReq->setParameter("notify_id", $notify_id);
			//通信对象
			$httpClient = new TenpayHttpClient();
			$httpClient->setTimeOut(5);
			//设置请求内容
			$httpClient->setReqContent($queryReq->getRequestURL());
			//后台调用
			if($httpClient->call()) {
				//设置结果参数
				$queryRes = new ClientResponseHandler();
				$queryRes->setContent($httpClient->getResContent());
				$queryRes->setKey($this->config['key']);
				if($resHandler->getParameter("trade_mode") == "1"){
					//判断签名及结果（即时到帐）
					//只有签名正确,retcode为0，trade_state为0才是支付成功
					if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $resHandler->getParameter("trade_state") == "0") {
						log_result("即时到帐验签ID成功");
						//取结果参数做业务处理
						$out_trade_no = $resHandler->getParameter("out_trade_no");
						//财付通订单号
						$transaction_id = $resHandler->getParameter("transaction_id");
						//金额,以分为单位
						$total_fee = $resHandler->getParameter("total_fee");
						//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
						$discount = $resHandler->getParameter("discount");
						//------------------------------
						//处理业务开始
						//------------------------------
						log_result("即时到帐后台回调成功");
						return true ;
					}
					else {
						//错误时，返回结果可能没有签名，写日志trade_state、retcode、retmsg看失败详情。
						//echo "验证签名失败 或 业务错误信息:trade_state=" . $resHandler->getParameter("trade_state") . ",retcode=" . $queryRes->                         getParameter("retcode"). ",retmsg=" . $queryRes->getParameter("retmsg") . "<br/>" ;
						log_result("即时到帐后台回调失败");
						echo false;
					}
				}
			}
			else{
				//通信失败
				echo false;
			}
		} 	
	}
	
	public function returnUrl($data){
		require_once ("ResponseHandler.class.php");
		require_once ("function.php");
		log_result("进入前台回调页面");
		/* 创建支付应答对象 */
		$resHandler = new ResponseHandler($data);
		$resHandler->setKey($this->config['key']);
		//判断签名
		if($resHandler->isTenpaySign()) {
			$notify_id = $resHandler->getParameter("notify_id");
			//商户订单号
			$out_trade_no = $resHandler->getParameter("out_trade_no");
			//财付通订单号
			$transaction_id = $resHandler->getParameter("transaction_id");
			//金额,以分为单位
			$total_fee = $resHandler->getParameter("total_fee");
			//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
			$discount = $resHandler->getParameter("discount");
			//支付结果
			$trade_state = $resHandler->getParameter("trade_state");
			//交易模式,1即时到账
			$trade_mode = $resHandler->getParameter("trade_mode");
			if("1" == $trade_mode ) {
				if( "0" == $trade_state){
					//echo "<br/>" . "即时到帐支付成功" . "<br/>";
					return true;
				} else {
					//当做不成功处理
					//echo "<br/>" . "即时到帐支付失败" . "<br/>";
					return false;
				}
			}elseif( "2" == $trade_mode  ) {
				if( "0" == $trade_state) {
					//echo "<br/>" . "中介担保支付成功" . "<br/>";
					return true;
				} else {
					return false;
					//当做不成功处理
					//echo "<br/>" . "中介担保支付失败" . "<br/>";
				}
			}
		} else {
			echo "<br/>" . "认证签名失败" . "<br/>";
			echo $resHandler->getDebugInfo() . "<br>";
		}
	}
}

?>